import { ImageProcessType } from '@utils/image-process/image-process-type.enum';
import { ProcessMenuTreeNode } from './process-menu-tree-node';

export class ProcessMenuTree {
  private rootNode = new ProcessMenuTreeNode({ title: 'root', type: null });

  static fromJson(json: ProcessMenuSchema[]) {
    const menu = new ProcessMenuTree();
    const root = menu.getRoot();
    appendNodeToMenu(root, json);
    return menu;
  }
  constructor() {

  }

  getRoot() {
    return this.rootNode;
  }

  getMenu() {
    return this.rootNode.children || [];
  }

}

function appendNodeToMenu(node: ProcessMenuTreeNode, children: ProcessMenuSchema[]) {
  const childrenNodes = children.map(item => {
    const isLeaf = Boolean(item.children);
    const itemNode = new ProcessMenuTreeNode({
      title: item.title,
      type: item.type,
      isLeaf,
    });
    if (item.children) {
      appendNodeToMenu(itemNode, item.children);
    }
    return itemNode;
  });
  node.appendChildren(childrenNodes);
}

export interface ProcessMenuSchema {
  title: string;
  type: ImageProcessType | null;
  children?: ProcessMenuSchema[];
}
